var express = require('express');
var router = express.Router();
var myCenterModal = require('../../database/model/myCenter/myCenterModal')
var userModel = require('../../database/model/userModel')
 router.post('/userCenter',(req,res)=>{
  var {username,userId} =req.body
  myCenterModal.find().then(data=>{
    new myCenterModal({  //【2】一条具体的数据实例
      username:username,
      userId:data.length++
    }).save().then(ress=>{
      res.status(200).send({
        msg:'请求myCenter成功',
      })
    })
  })
 })
router.put('/userInfo', (req, res) => {
  var { 
    avator, 
    id, 
    age,
    Email,
    adress,
    detailAdress,
    nativePlace,
    company, 
    isVip,
    hireDate,
    profile, 
    phone, 
    telPhone, 
    sex, 
  } = req.body
  userModel.findOneAndUpdate({ _id: id },{ $set: {
    avator, 
    id, 
    age,
    Email,
    adress,
    detailAdress,
    nativePlace,
    company, 
    isVip,
    hireDate,
    profile, 
    phone, 
    telPhone, 
    sex,
   } },{new:true} , (err, data) => {
      if (err) {//$set为默认操作 如果没有字段自动新增
        console.log('数据库发生错误')
      }
      else if (!data) {
        console.log('未查找到相关数据')
        console.log(data)
      }
      else if (data) {
        console.log('修改数据成功')
        console.log(data)
        let { avator, _id } = data
        res.send({
          msg: "修改成功",
          code: 1,
          data: { avator, _id }
        })
      }
    })
})
router.get('/userInfo', (req, res) => {
  var { id } = req.query
  userModel.find({ _id: id },(err, data) => {
    if (data) {
      console.log('查找数据完毕')
      let obj = JSON.parse(JSON.stringify(data[0]))
      delete obj.password
      delete obj.__v
      res.send({
        msg: "查询成功",
        code: 1,
        data: obj
      })
    } else { 
      res.send({
        msg: '暂无数据',
        code: 0,
        data: null
      })
    }
    })
})
router.put('/upload',(req,res)=>{  //修改用户头像
  let {_id,avator} = req.body
  console.log("_id,avator",_id,avator)
  userModel.findOneAndUpdate({_id},{$set:{avator}},{new:true},(err,data)=>{//$set为默认操作 如果没有字段自动新增
    if(err) {
      console.log('数据库发生错误')
    }
    else if(!data) {
      console.log('未查找到相关数据')
      console.log(data)
    }
    else if(data){
      console.log('修改数据成功')
      console.log(data)
      let {avator,_id}=data
      res.send({
        msg:"修改成功",
        code:1,
        data:{avator,_id}
      })
    }
  })
})
   

   
module.exports = router;